package com.uam.utils;

import com.alibaba.fastjson.JSONObject;
import com.opencsv.CSVWriter;
import com.opencsv.ICSVWriter;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.opencsv.exceptions.CsvDataTypeMismatchException;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;

import javax.servlet.http.HttpServletResponse;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.List;

/**
 * @author uam
 * @create 2023/12/4 15:50
 * @email uam@uam.com
 */
public class CsvUtil {
    public static <T> void createCsvFile(List<T> data, String filePath, String fileName, HttpServletResponse response) throws IOException {
        Writer writer = null;
        //导出并保存到本地
      /*  if(filePath != null){
            writer = new FileWriter(filePath + fileName + ".csv");
        }*/
        //导出并随请求返回以供用户下载
        if (response != null) {
            response.reset();
            response.setContentType("APPLICATION/OCTET-STREAM");
            fileName = new String(fileName.getBytes("UTF-8"), "UTF-8");
            response.setHeader("Content-disposition", "attachment;  filename=" + fileName + ".csv");
            response.setCharacterEncoding("UTF-8");
            writer = response.getWriter();
        }
        if (writer == null) {
            return;
        }
        try {
            writer.write(new String(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF}));
            CSVWriter csvWriter =
                    new CSVWriter(writer, ICSVWriter.DEFAULT_SEPARATOR, ICSVWriter.NO_QUOTE_CHARACTER,
                            ICSVWriter.NO_ESCAPE_CHARACTER, ICSVWriter.DEFAULT_LINE_END);
            StatefulBeanToCsv<T> beanToCsv = new StatefulBeanToCsvBuilder<T>(writer)
                    .withMappingStrategy(new CustomMappingStrategy(data.get(0).getClass()))
                    .build();
            beanToCsv.write(data);
            csvWriter.close();
        } catch (CsvRequiredFieldEmptyException e) {
            throw new RuntimeException(e);
        } catch (CsvDataTypeMismatchException e) {
            throw new RuntimeException(e);
        }
        writer.close();
    }

    public static <T> void createJSONFile(List<T> datas, String filePath, String fileName, HttpServletResponse response) throws IOException {
        Writer writer = null;
        //导出并保存到本地
      /*  if(filePath != null){
            writer = new FileWriter(filePath + fileName + ".csv");
        }*/
        //导出并随请求返回以供用户下载
        if (response != null) {
            response.reset();
            response.setContentType("APPLICATION/OCTET-STREAM");
            fileName = new String(fileName.getBytes("UTF-8"), "UTF-8");
            response.setHeader("Content-disposition", "attachment;  filename=" + fileName + ".json");
            response.setCharacterEncoding("UTF-8");
            writer = response.getWriter();
        }
        if (writer == null) {
            return;
        }

        for (int i = 0; i < datas.size(); i++) {
            T t = datas.get(i);
            writer.append(JSONObject.toJSONString(t));
            if (i==datas.size()-1){
                break;
            }else {
                writer.append("\r\n");
            }
            if ((i+1)%5==0){
                writer.flush();
            }
        }

        writer.close();
    }

    public static <T> void createJSONFile(String data, String fileName, HttpServletResponse response) throws IOException {
        Writer writer = null;
        //导出并随请求返回以供用户下载
        if (response != null) {
            response.reset();
            response.setContentType("APPLICATION/OCTET-STREAM");
            fileName = new String(fileName.getBytes("UTF-8"), "UTF-8");
            response.setHeader("Content-disposition", "attachment;  filename=" + fileName);
            response.setCharacterEncoding("UTF-8");
            writer = response.getWriter();
        }

        if (writer == null) {
            return;
        }

        writer.append(data);
        writer.flush();
        writer.close();
    }
}
